// pages/list/list.js
const db = wx.cloud.database()
const app = getApp()
import Dialog from '../../vant/dialog/dialog'
import Toast from '../../vant/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showBackArrow: true,
    showLogo: false,
    showText: false,
    current: '123',
    list: {
      title: '购物车'
    },
    cardChecked: false,
    goodsChecked: [],
    checkAll: false,
    cartData: [],
    priceSum: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getListData()
  },
  onShow(options) {
    if(!this.data.showSubmitPop) {
      this.setData({
        priceSum: 0,
        checkAll: false
      })
      this.getListData()
    }
  },
  changeCardCheckbox(e) {
    console.log(e)
  },
  handleChange(e) {
    console.log(e)
  },
  onClickDelete(e) {
    console.log(e)
  },
  getListData() {
    let openId = app.globalData.openid
    if(openId) {
      // 用户已登录
      db.collection('cart_list').where({
        _openid: openId,
        enable: 1
      })
      .get().then(res => {
        this.setData({
          cartData: res.data
        })
        let goodsCheckedArr = []
        // 循环获取产品信息
        for(let i = 0, len = res.data.length; i < len; i ++) {
          let goodId = res.data[i].goodId
          wx.cloud.callFunction({
            name: 'getGoodInfo',
            data: {goodId: goodId},
            success: res => {
              // 获取每个产品的信息，存入goodDetail中
              this.data.cartData[i].goodDetail = {}
              let param = {}
              let string = `cartData[${i}].goodDetail`
              param[string] = res.result.data[0]
              this.setData(param)
            },
            fail: err => {
              Toast.fail('获取产品信息失败' + i)
            }
          })
          // 将所有产品的checkbox设置为false
          goodsCheckedArr.push(false)
        }
        this.setData({
          goodsChecked: goodsCheckedArr
        })
      })
    } else {
      //用户未登录
    }
  },
  onChangeCheckbox(e) {
    let index = e.target.dataset.index
    let param = {}
    let string = `goodsChecked[${index}]`
    param[string] = !this.data.goodsChecked[index]
    this.setData(param)
    let priceSum = 0
    let cartData = this.data.cartData
    let isAllSelect = true
    // 判断是否全选
    for(let i = 0, len = this.data.goodsChecked.length; i < len; i ++) {
      if(!this.data.goodsChecked[i]) {
        isAllSelect = false
      } else {
        priceSum += cartData[i].goodDetail.price * cartData[i].count
      }
    }
    // 购物车全选
    this.setData({
      checkAll: isAllSelect,
      priceSum: priceSum * 100 //单位是分
    })
  },
  cartCheckedAll() {
    // 点击全选按钮
    let priceSum = 0
    let cartData = this.data.cartData
    for(let i = 0, len = this.data.goodsChecked.length; i < len; i ++) {
      if(!this.data.checkAll) {
        this.data.goodsChecked[i] = true
        priceSum += cartData[i].goodDetail.price * cartData[i].count
      } else {
        this.data.goodsChecked[i] = false
      }
    }
    this.setData({
      goodsChecked: this.data.goodsChecked,
      checkAll: !this.data.checkAll,
      priceSum: priceSum * 100 //单位是分
    })
  },
  onChangeStepper(e) {
    let index = e.target.dataset.index
    let count = e.detail
    let param = {}
    let string = `cartData[${index}].count`
    param[string] = count
    this.setData(param)
  },
  tabDelete(e) {
    // 点击删除按钮的ajax操作
    let {id, index} = e.target.dataset
    Dialog.confirm({
      title: '确认删除？',
      message: '确认删除？'
    }).then(() => {
      db.collection('cart_list').doc(id).update({
        data: {
          "enable": 0
        }
      })
      .then(res => {
        this.getListData()
      })
      .catch(console.error)
    }).catch(() => {
      // on cancel
    })
  },
  clickImg() {
    console.log('click')
  },
  jumpToDetail(e) {
    let index = e.target.dataset.index
    let goodId = this.data.cartData[index].goodDetail.goodId
    wx.navigateTo({
      url: '/pages/detail/detail?goodId=' + goodId
    })
  },
  onClickSubmit(e) {
    // 获取用户选择的商品信息
    this.data.chosenGoodsList = []
    for(let i = 0, len = this.data.goodsChecked.length; i < len; i ++) {
      if(this.data.goodsChecked[i]) {
        this.data.chosenGoodsList.push(this.data.cartData[i])
      }
    }
    // 用户选择了商品
    if(this.data.chosenGoodsList.length > 0) {
      let goodsList = JSON.stringify(this.data.chosenGoodsList)
      wx.navigateTo({
        url: `/pages/order/order?listData=${goodsList}&priceSum=${this.data.priceSum}`
      })
    } else {
      Toast.fail('请选择商品！')
    }
  }
})